package com.bootdo.common.utils;

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.request.GetLogsRequest;
import com.aliyun.openservices.log.response.GetLogsResponse;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class AliyunLogUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunLogUtil.class);

    public static List<QueriedLog> queryByPage_airmboll(long start, long end, String yesterday) {
        long temp = 0;
        try {
            temp = new SimpleDateFormat("yyyy-MM-dd").parse(yesterday).getTime();
            int from = (int) (temp / 1000 - 3600);
            int to = from + 93600;
            long start_time_stamp = temp;
            long end_time_stamp = temp + 86400000;
            String query = "|select channel_id,imei,brand,sys_ver,device_model,id,time_stamp,client_ip,sdk_id from "
                    + AliyunLogConstant.ALIYUN_LOGSTORE_AIRMBOLL
                    + " where   id>=" + start + " and id<" + end
                    + " and time_stamp >=" + start_time_stamp
                    + " and time_stamp <" + end_time_stamp
                    + " order by id limit 10000";
            return queryByPage(from, to, AliyunLogConstant.ALIYUN_LOGSTORE_AIRMBOLL, query);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Client getClient() {
        Client client = new Client(AliyunLogConstant.ALIYUN_ENDPOINT, AliyunLogConstant.ALIYUN_ACCESSKEYID, AliyunLogConstant.ALIYUN_ACCESSKEYSECRET);
        return client;
    }

    private static ArrayList<QueriedLog> queryByPage(int from, int to, String logStore, String query) {
        ArrayList<QueriedLog> list = new ArrayList<>();
        GetLogsResponse res4 = null;
        // 对于每个 log offset,一次读取 10 行 log，如果读取失败，最多重复读取 3 次。
        for (int retry_time = 0; retry_time < 5; retry_time++) {
            try {
                GetLogsRequest req4 = new GetLogsRequest(AliyunLogConstant.ALIYUN_PROJECT, logStore, from, to, null, query);
                res4 = getClient().GetLogs(req4);
                list = res4.GetLogs();
                if (res4 != null && res4.IsCompleted()) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
